package com.tanchengjin.admin.interceptions;

import com.tanchengjin.admin.SystemConstants;
import com.tanchengjin.admin.config.AdminConfig;
import com.tanchengjin.admin.model.dao.AdminUserMapper;
import com.tanchengjin.admin.model.pojo.AdminUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 * @author tanchengjin
 */
@Component
public class AdminAuthenticationInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(AdminAuthenticationInterceptor.class);

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private AdminConfig adminConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (adminConfig.isDebug()) {
            AdminUser adminUser = adminUserMapper.selectByPrimaryKey(1);
            request.getSession().setAttribute(SystemConstants.adminUserSessionKey, adminUser);
        }

        Object attribute = request.getSession().getAttribute(SystemConstants.adminUserSessionKey);
        if (attribute != null) {
            return true;
        }

        response.sendRedirect(adminConfig.getPrefix() + "/auth/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
